package com.mapaoer.user.controller;

import com.mapaoer.user.entity.Permission;
import com.mapaoer.user.entity.Role;
import com.mapaoer.user.service.RolePermissionService;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
@Api(tags = "系统管理 - 角色权限管理")
public class RolePermissionController {

    private final RolePermissionService rolePermissionService;

    @PostMapping("/roles")
    @ApiOperation("创建角色")
    public ResponseEntity<Role> createRole(
            @RequestParam String name,
            @RequestParam(required = false) String description) {
        return new ResponseEntity<>(rolePermissionService.createRole(name, description), HttpStatus.CREATED);
    }

    @PostMapping("/roles/{roleId}/permissions")
    @ApiOperation("为角色分配权限")
    public ResponseEntity<Role> assignPermissionsToRole(
            @PathVariable Long roleId,
            @RequestBody List<Long> permissionIds) {
        return ResponseEntity.ok(rolePermissionService.assignPermissionsToRole(roleId, permissionIds));
    }

    @PostMapping("/users/{userId}/roles")
    @ApiOperation("为用户分配角色")
    public ResponseEntity<Void> assignRolesToUser(
            @PathVariable Long userId,
            @RequestBody List<Long> roleIds) {
        rolePermissionService.assignRolesToUser(userId, roleIds);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/permissions")
    @ApiOperation("创建权限")
    public ResponseEntity<Permission> createPermission(
            @RequestParam String name,
            @RequestParam(required = false) String description,
            @RequestParam String permissionKey) {
        return new ResponseEntity<>(rolePermissionService.createPermission(name, description, permissionKey), HttpStatus.CREATED);
    }

    @GetMapping("/roles")
    @ApiOperation("获取所有角色")
    public ResponseEntity<List<Role>> getAllRoles() {
        return ResponseEntity.ok(rolePermissionService.getAllRoles());
    }

    @GetMapping("/permissions")
    @ApiOperation("获取所有权限")
    public ResponseEntity<List<Permission>> getAllPermissions() {
        return ResponseEntity.ok(rolePermissionService.getAllPermissions());
    }

    @GetMapping("/users/{userId}/roles")
    @ApiOperation("获取用户角色列表")
    public ResponseEntity<List<Role>> getUserRoles(@PathVariable Long userId) {
        return ResponseEntity.ok(rolePermissionService.getUserRoles(userId));
    }
}